package service;


import book.Book;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import util.PropertiesUtil;
import util.StringUtil;

public class Robot {
	public static String encoding = "gb2312";
	public static String res_list_beginPoint;
	public static String res_list_endPoint;
	public static String regex_book;
	public static String regex_book_debar;
	public static int book_id_index;
	public static int book_name_index;
	public static int book_author_index;
	public static String base_img_url;
	public static String base_txtfile_url;
	public static String base_chmfile_url;
	public static long sleep_time = 3000L;
	public static boolean isNeedLoadConfig = true;
	
	public static String book_url;

	public Robot() {
		loadConfig();
	}

	public void loadConfig() {
		if (isNeedLoadConfig) {
			try {
				Map map = PropertiesUtil.loadPropertiesFile();
				String temp = new String();
				encoding = (String) map.get("encoding");
				res_list_beginPoint = (String) map.get("res_list_beginPoint");
				res_list_endPoint = (String) map.get("res_list_endPoint");
				regex_book = (String) map.get("regex_book");
				regex_book_debar = (String) map.get("regex_book_debar");
				temp = (String) map.get("book_id_index");
				if (temp != null) {
					book_id_index = Integer.parseInt(temp);
				}
				temp = (String) map.get("book_name_index");
				if (temp != null) {
					book_name_index = Integer.parseInt(temp);
				}
				temp = (String) map.get("book_author_index");
				if (temp != null) {
					book_author_index = Integer.parseInt(temp);
				}
				temp = (String) map.get("sleep_time");
				if (temp != null) {
					sleep_time = Long.parseLong(temp);
				}
				base_img_url = (String) map.get("base_img_url");
				
				base_txtfile_url = (String) map.get("base_txtfile_url");
				base_chmfile_url = (String) map.get("base_chmfile_url");
				
				book_url = (String)map.get("book_url");
			} catch (Exception e) {
				e.printStackTrace();
			}
			isNeedLoadConfig = false;
		}
	}
	
	public List parseBooks() throws IOException, InterruptedException {
		return this.parseBooks(null);
	}
	
	public List parseBooks(String url) throws IOException, InterruptedException {
		if(url == null || "".equals(url)) url = this.book_url;
		List list = new ArrayList();
		String s  = getOneHtml(url, encoding);
		List bs = getContentsByRegexAndDebar(regex_book, regex_book_debar, s);
		String bookId = new String();
		String name = new String();
		String author = new String();
		String txtUrl = new String();
		String chmUrl = new String();
		String imgUrl = new String();
		for (int i = 0; i < bs.size(); i++) {
			Thread.sleep(sleep_time);
			s = (String) bs.get(i);
			String g[] = s.split(",");
			bookId = g[book_id_index];
			name = g[book_name_index];
			author = g[book_author_index];
			txtUrl = (new StringBuilder(String.valueOf(base_txtfile_url))).append(
					bookId).append(".txt").toString();
			chmUrl = (new StringBuilder(String.valueOf(base_chmfile_url))).append(
					bookId).append(".chm").toString();
			imgUrl = (new StringBuilder(String.valueOf(base_img_url))).append(
					bookId).append(".jpg").toString();
			
			Book book = new Book();
			book.setBookId(bookId);
			book.setName(name);
			book.setAuthor(author);
			book.setTxtUrl(txtUrl);
			book.setChmUrl(chmUrl);
			book.setImgUrl(imgUrl);
			list.add(book);
		}

		return list;
	}

	public List getContentsByRegex(String regex, String s) {
		List list = new ArrayList();
		Pattern pa = Pattern.compile(regex, 32);
		for (Matcher ma = pa.matcher(s); ma.find(); list.add(ma.group())) {
		}
		return list;
	}

	public List getContentsByRegexAndDebar(String regex, String regex_debar,
			String s) {
		List list = new ArrayList();
		Pattern pa = Pattern.compile(regex, 32);
		Matcher ma = pa.matcher(s);
		String str = "";
		for (; ma.find(); list.add(str)) {
			str = ma.group().replaceAll(regex_debar, "");
		}

		return list;
	}

	public String getContentByRegex(String regex, String s) {
		List list = new ArrayList();
		String ss = "";
		Pattern pa = Pattern.compile(regex, 32);
		Matcher ma = pa.matcher(s);
		if (ma.find()) {
			list.add(ma.group());
		}
		if (list.size() > 0) {
			ss = (String) list.get(0);
		}
		return ss;
	}

	public String getContentByRegexAndDebar(String regex, String regex_debar,
			String s) {
		List list = new ArrayList();
		String ss = "";
		Pattern pa = Pattern.compile(regex, 32);
		Matcher ma = pa.matcher(s);
		String str = new String();
		if (ma.find()) {
			str = ma.group().replaceAll(regex_debar, "");
			list.add(str);
		}
		if (list.size() > 0) {
			ss = (String) list.get(0);
		}
		return ss;
	}

	public String getOneHtml(String htmlurl, String encoding)
			throws IOException {
		if (htmlurl == null || htmlurl.trim().length() <= 0) {
			return null;
		}
		boolean bool = StringUtil.chk("^http://", htmlurl.trim()
				.toLowerCase());
		if (!bool) {
			return null;
		}
		
		StringBuffer sb = new StringBuffer();
		BufferedReader in = null;
		InputStream is = null;
		URL url = new URL(htmlurl);
		HttpURLConnection http = (HttpURLConnection) url.openConnection();
		try {
			http
					.setRequestProperty("User-Agent",
							"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.8.1) Gecko/Firefox/2.0");
			String contentType = http.getContentType();
			String myencoding = null;
			if (contentType != null) {
				int index = contentType.indexOf("charset=");
				if (index != -1) {
					myencoding = contentType.substring(index + 8).trim();
				}
			}
			if (myencoding != null && myencoding.trim().length() > 0) {
				encoding = myencoding;
			}
			if (encoding == null || encoding.trim().length() <= 0) {
				encoding = "gb2312";
			}
			is = http.getInputStream();
			in = new BufferedReader(new InputStreamReader(is, encoding));
			String temp;
			while ((temp = in.readLine()) != null) {
				sb.append(temp);
			}
		} catch (MalformedURLException me) {
			System.out.println((new StringBuilder(
							"\u8F93\u5165\u7684URL\u683C\u5F0F\u6709\u95EE\u9898\uFF01 url:"))
							.append(htmlurl).toString());
			me.getMessage();
			throw me;
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		}finally{
			try {
				in.close();
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (http != null) {
				http.disconnect();
			}
		}
		return sb.toString();
	}

	public String filterFileName(String s) {
		if (s == null || s.trim().length() <= 0) {
			return "\u672A\u547D\u540D";
		}
		s = s.replaceAll("\\\\|\\/|:|\\*|\\?|\"|<|>|\\|\\s", "");
		if (s.trim().length() <= 0) {
			s = "\u672A\u547D\u540D";
		}
		return s;
	}

	public String getUrlFromLinkTag(String baseurl, String urlTag) {
		if (urlTag == null || urlTag.trim().length() <= 0 || baseurl == null
				|| baseurl.trim().length() <= 0) {
			return null;
		} else {
			String href = getContentByRegex("(href|HREF)=(\"|'| |).*?(\"|'| )",
					urlTag);
			urlTag = href.replaceAll("(href|HREF)=|'|\"", "");
			String url = getFullUrl(baseurl, urlTag);
			return url;
		}
	}

	public String getUrlFromLinkTagByStandard(String baseurl, String urlTag) {
		if (urlTag == null || urlTag.trim().length() <= 0 || baseurl == null
				|| baseurl.trim().length() <= 0) {
			return null;
		} else {
			String href = getContentByRegex("(href|HREF)=(\"|').*?(\"|')",
					urlTag);
			urlTag = href.replaceAll("(href|HREF)=|'|\"", "");
			String url = getFullUrl(baseurl, urlTag);
			return url;
		}
	}

	public List getUrlsFromLinkTagsByStandard(String regex, String baseurl,
			String urlTags) {
		if (urlTags == null || urlTags.trim().length() <= 0 || baseurl == null
				|| baseurl.trim().length() <= 0) {
			return null;
		}
		List list = new ArrayList();
		Pattern pa = Pattern.compile(regex, 32);
		Matcher ma = pa.matcher(urlTags);
		String str = new String();
		for (; ma.find(); list.add(str)) {
			str = ma.group();
			str = getUrlFromLinkTagByStandard(baseurl, str);
		}

		return list;
	}

	public String getFullUrl(String baseurl, String myurl) {
		if (myurl == null || myurl.trim().length() <= 0 || baseurl == null
				|| baseurl.trim().length() <= 0) {
			return null;
		}
		myurl = myurl.trim().replaceAll(" ", "%20");
		boolean bool = StringUtil.chk("^(http|HTTP)://", myurl.trim());
		if (!bool) {
			int index = myurl.indexOf("/");
			if (index < 0) {
				myurl = (new StringBuilder(String.valueOf(baseurl.substring(0,
						baseurl.lastIndexOf("/") + 1)))).append(myurl)
						.toString();
			} else {
				int flag = myurl.indexOf("./");
				if (flag >= 0) {
					myurl = (new StringBuilder(String.valueOf(baseurl
							.substring(0, baseurl.lastIndexOf("/"))))).append(
							myurl.replaceFirst(".", "")).toString();
				} else {
					myurl = (new StringBuilder(String.valueOf(baseurl
							.substring(0, baseurl.indexOf("/", 7))))).append(
							myurl).toString();
				}
			}
		}
		return myurl.trim();
	}

}
